<template>
  <div class="mt-1">
    <van-form>
      <van-field
        v-model="f_value"
        label="发货工厂"
        :label-width="labelWidth"
        clickable
        readonly
        arrow-direction="down"
        is-link
        :value="f_value"
        placeholder="请选择工厂代码"
        @click="Choose"
      >
      </van-field>
      <van-popup v-model="showPicker_f" round position="bottom">
        <van-picker
          title="工厂代码"
          show-toolbar
          :columns="splant"
          @cancel="showPicker_f = false"
          @confirm="onAffirm"
        />
      </van-popup>
      <!-- 收货工厂 -->
      <van-field
        v-model="s_value"
        label="收货工厂"
        :label-width="labelWidth"
        clickable
        readonly
        arrow-direction="down"
        is-link
        :value="s_value"
        placeholder="请选择工厂代码"
        @click="showPicker = true"
      >
      </van-field>
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          title="工厂代码"
          show-toolbar
          :columns="rplant"
          @cancel="showPicker = false"
          @confirm="onSure"
        />
      </van-popup>
      <!-- 库存状态 -->
      <!-- <van-field
        readonly
        clickable
        arrow-direction="down"
        is-link
        :label-width="labelWidth"
        label="库存状态"
        :value="kc_value"
        placeholder="请选择库存状态"
        @click="showPicker_kc = true"
      />
      <van-popup v-model="showPicker_kc" round position="bottom">
        <van-picker
          show-toolbar
          :columns="stockStatus"
          @cancel="showPicker_kc = false"
          @confirm="onAckonwledge"
        />
      </van-popup> -->
      <!-- 拍码 -->
      <van-field
        v-model="code"
        :label-width="labelWidth"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
        placeholder="请扫描拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 55vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>

      <van-row
        gutter="30"
        justify="center"
        type="flex"
        style="margin-top: 1rem"
      >
        <van-col span="7">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="warning" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-send-data :ShowDataB="ShowData" @get-val="Sure" />
      </van-popup>
    </van-form>

    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="请输入要修改的数量"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入数量"
      />
    </van-dialog>
  </div>
</template>

<script>
import { getVRplant } from "../../assets/api/get";
import { InformationSubmit, getDetail } from "../../assets/api/post";
import { parseQRCode, toast } from "../../untils/commion";
import { AgGridVue } from "ag-grid-vue";
import ShowSendData from "../../components/ShowSendDate.vue";
import { AgGrid } from "../../minx/AgGrid";

export default {
  components: { AgGridVue, ShowSendData },
  mixins: [AgGrid],
  data() {
    return {
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      labelWidth: "7em",
      titles: new Map().set(5, "STO发货"),
      type: null,
      code: "",
      f_value: "CN01",
      s_value: "",
      plant: "",
      plantcode: "",
      inventorystatus: "",
      kc_value: "U",
      ShowStatue: false,
      showPicker_f: false,
      showPicker: false,
      showPicker_kc: false,
      columnDefs: [
        { headerName: "物料", field: "productid", flex: 1.5 },
        { headerName: "拍号", field: "uniqueid", flex: 2 },
        { headerName: "数量", field: "stockquantity", flex: 1.5 },
      ],
      stockStatus: ["U", "X", "S"],
      copysplant: [],
      copyrplant: [],
      splant: [],
      rplant: [],
      rowData: [],
      detailData: [],
      ShowData: {}, //展示的数据
      newStatues: "",
    };
  },
  watch: {
    code(newValue) {
      if (this.f_value && this.s_value && this.kc_value) {
        if (newValue.length > 9) {
          let paresqrdata = parseQRCode(newValue);
          if (paresqrdata) {
            if (
              !this.rowData.find((it) => it.uniqueid == paresqrdata.palletNo)
            ) {
              //获取数据
              this.getDetailInfo(paresqrdata.palletNo);
              paresqrdata = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
      } else {
        toast("请选择工厂和状态");
      }
      this.code = "";
    },
  },
  methods: {
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("表格数据为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    //弹出确认键
    onAffirm(f_value) {
      this.f_value = f_value;
      this.showPicker_f = false;
      this.changeSPlantCode();
    },
    onSure(s_value) {
      this.s_value = s_value;
      this.showPicker = false;
    },
    onAckonwledge(kc_value) {
      this.kc_value = kc_value;
      this.showPicker_kc = false;
    },
    //发货工厂代码，将pl中的所有splant放入copys，
    getSPlant(PL) {
      for (var i in PL) {
        this.copysplant.push(PL[i].splant);
      }
      for (var j in this.copysplant) {
        if (this.splant.indexOf(this.copysplant[j]) == -1) {
          this.splant.push(this.copysplant[j]);
        }
      }
    },
    //改变发货，收货也变
    changeSPlantCode() {
      let PL = this.plant;
      this.rplant = [];
      for (var m in PL) {
        if (PL[m].splant == this.f_value) {
          this.rplant.push(PL[m].rplant);
        }
      }
    },
    //收货工厂代码
    getRPlant(PL) {
      var n = 0;
      for (var m in PL) {
        if (PL[m].splant == this.copysplant[n]) {
          this.rplant.push(PL[m].rplant);
        }
      }
    },
    Choose() {
      this.showPicker_f = true;
      this.s_value = "";
    },
    //检查状态
    Check() {
      let kc = "";
      switch (this.kc_value) {
        case "U":
          kc = "U";
          break;
        case "S":
          kc = "S";
          break;
        case "X":
          kc = "X";
          break;
      }
      if (kc == this.inventorystatus && this.f_value == this.plantcode) {
        this.rowData.push({
          make: this.$store.state.uniqueid,
          model: this.$store.state.productid,
          price: this.$store.state.stockquantity,
        });
      } else {
        this.$toast.fail("发货工厂或库存状态不匹配");
      }
    },
    //获取后台信息
    async getDetailInfo(val) {
      let res = await getDetail(val);
      if (res.status == 200) {
        this.newStatues = res.data[0].inventorystatus;
        this.ShowData = JSON.parse(JSON.stringify(res.data[0]));
        if (this.ShowData) {
          this.ShowStatue = true;
          this.rowData.push(res.data[0]);
        }
      } else {
        toast(res.msg);
      }
      this.code = "";
    },
    //传回来把组件关闭
    Sure() {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.getOther();
      setTimeout(() => {
        this.$refs.code.focus();
      }, 300);
    },
    //主列表数据
    getOther() {
      this.detailData.push({
        PalletNo: this.ShowData.uniqueid,
        MATERIALSKU: this.ShowData.productid,
        ActSumBox: this.ShowData.stockquantity,
        SortCode: 1,
        BatchNo: this.ShowData.batchno,
      });
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    async onSubmit() {
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        let type = "SO";
        let submit = {
          BillType: "SO",
          BillTypeName: "STO发货",
          OutTime: this.getNowDate(),
          CreatedId: JSON.parse(localStorage.getItem("userid")),
          CreatedName: JSON.parse(localStorage.getItem("username")),
          Plant: this.f_value,
          soldto: this.s_value.substring(5, 10),
          shiptoid: this.s_value.substring(5, 10),
          receivingPlantname: this.s_value,
          shiptoname: this.s_value,
          Rer01: this.newStatues,
          fhckname: "",
          F_zzfhlx: "",
          ModifiedOn: "",
          ModifiedName: "",
          CreatedOn: "",
          Comment: "",
          zzfhlxradio1: "",
          fhckid: "",
        };
        let res = await InformationSubmit(
          type,
          JSON.stringify(submit),
          JSON.stringify(this.detailData)
        );
        if (res.d.state == "success") {
          this.rowData = [];
          this.detailData = [];
          if (this.rowData.length == 0) {
            toast(res.d.message);
          }
        } else {
          toast(res.d.message);
        }
        // console.log(res);
      }
    },
    //自动获取工厂信息
    async getBusinessInfo() {
      let res = await getVRplant();
      if (res.status == 200) {
        this.plant = res.data.data;
        var PL = this.plant;
        //获取收入库数组
        this.getSPlant(PL);
        this.getRPlant(PL);
      } else {
        toast("后台发生错误，请与管理员联系");
      }
    },
    //点击弹出修改数量弹窗
    updateNum() {
      this.selectDate = this.gridApi.getSelectedRows();
      if (this.selectDate[0] == null) {
        this.$toast("请选择要修改的数据");
      } else {
        this.ifShowUpdateNum = true;
      }
    },
    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "" || this.needUpdateNum == 0) {
        this.$toast("未输入数量无法修改");
        this.needUpdateNum = "";
      } else {
        this.selectDate[0].stockquantity = this.needUpdateNum;
        this.gridApi.applyTransaction({ update: this.selectDate });
        this.detailData.forEach((item) => {
          if (this.selectDate[0].uniqueid == item.PalletNo) {
            item.ActSumBox = Number(this.needUpdateNum);
          }
        });
        this.needUpdateNum = "";
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.getBusinessInfo();
    this.closeEnter();
  },
};
</script>

<style lang="less" scope>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
.van-cell {
  padding: 0.5rem 1rem !important;
}
</style>